<?php
declare (strict_types = 1);

namespace app\controller\v1;

use app\model\ScenicSpots;
use app\model\ScenicSpotsLike;
use app\model\Tickets;
use think\Request;

class TravelController extends BaseAPIController
{


    //获取景点列表
    public function getSpotList()
    {
        $uid = $this->userService->getCurrentUserId();
        $spotList = ScenicSpots::where('status',1)
        ->select()
        ->toArray();
        $spotList = array_map(function($item) use ($uid){
            // valid_start,valid_end
            $item['price']=Tickets::where('status',1)->where('valid_start','<=',date('Y-m-d'))->where('valid_end','>=',date('Y-m-d'))->order('price','asc')->value('price');
            $item['price']=empty($item['price'])?0:$item['price'];
            $item['rating']=5;
            $item['review_count']='99+';
            $item['is_favorite']=false;
            if ($uid) {
                $item['is_favorite']=ScenicSpotsLike::where('user_id',$uid)->where('spots_id',$item['id'])->count()>0;
            }
            return $item;
        },$spotList);
        return $this->success($spotList);
    }

    // 获取景点详情
    public function getScenicSpotDetail(Request $request)
    {
        $id = $request->param('id','');
        if (!$id) {
            return $this->error('参数错误');
        }
        $scenicSpot = ScenicSpots::with(['tickets' => function($query) use ($id){
            $query->where('status',1)->where('valid_start','<=',date('Y-m-d'))->where('valid_end','>=',date('Y-m-d'));
        }])->find($id);
        if (!$scenicSpot) {
            return $this->error('景点不存在');
        }
       
        $scenicSpot  =$scenicSpot->toArray();
       
        $scenicSpot['open_time'] = '09:00-21:00';//date('H:i',strtotime($scenicSpot->open_time));
        // $scenicSpot['cover_image']=env('IMAGE_URL').$scenicSpot['cover_image'];
        // $scenicSpot['images']=explode(',',$scenicSpot['images']);
        // $scenicSpot['images']=array_map(function($item){
        //     return env('IMAGE_URL').$item;
        // },$scenicSpot['images']);
        return $this->success($scenicSpot);
    }


    // 景点喜欢表
    public function spotLike()
    {
        $uid = $this->userService->getCurrentUserId();
        $spotsId = $this->request->get('spots_id','');
        if (!$spotsId) {
            return $this->error('参数错误',400);
        }
        $spotLike = ScenicSpotsLike::where('user_id',$uid)->where('spots_id',$spotsId)->find();
        if (!$spotLike) {
            ScenicSpotsLike::create([
                'user_id'=>$uid,
                'spots_id'=>$spotsId,
                'create_time'=>date('Y-m-d H:i:s'),
            ]);
        }else{
            ScenicSpotsLike::where('id',$spotLike['id'])->delete();
        }
        return $this->success();
    }
}
